<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Post;
use App\Models\Notification;
use App\Models\PostFavorite;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Inertia\Inertia;

class ProfileController extends Controller
{
    /**
     * 显示用户个人主页
     */
    public function show(User $user)
    {
        $user->loadCount(['followers', 'following', 'posts']);

        // 获取用户的公开文章
        $posts = Post::where('user_id', $user->id)
            ->published()
            ->approved()
            ->when(!auth()->check() || auth()->id() !== $user->id, function ($query) {
                // 非本人只能看到公开文章
                $query->where('access_level', 'public');
            })
            ->latest('published_at')
            ->paginate(10);

        $isFollowing = auth()->check() ? auth()->user()->isFollowing($user) : false;

        return Inertia::render('Profile/Show', [
            'user' => $user,
            'posts' => $posts,
            'isFollowing' => $isFollowing,
            'isOwnProfile' => auth()->id() === $user->id,
        ]);
    }

    /**
     * 显示编辑个人资料页面
     */
    public function edit()
    {
        $this->middleware('auth');

        return Inertia::render('Profile/Edit', [
            'user' => auth()->user(),
        ]);
    }

    /**
     * 更新个人资料
     */
    public function update(Request $request)
    {
        $this->middleware('auth');

        $user = auth()->user();

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'bio' => 'nullable|string|max:500',
            'website' => 'nullable|url|max:255',
            'github' => 'nullable|string|max:255',
            'twitter' => 'nullable|string|max:255',
            'linkedin' => 'nullable|string|max:255',
            'location' => 'nullable|string|max:255',
            'occupation' => 'nullable|string|max:255',
            'allow_email_notifications' => 'boolean',
        ]);

        $user->update($validated);

        return back()->with('success', '个人资料更新成功');
    }

    /**
     * 上传头像
     */
    public function uploadAvatar(Request $request)
    {
        $this->middleware('auth');

        $request->validate([
            'avatar' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);

        $user = auth()->user();

        // 删除旧头像
        if ($user->avatar && Storage::exists($user->avatar)) {
            Storage::delete($user->avatar);
        }

        // 保存新头像
        $path = $request->file('avatar')->store('avatars', 'public');
        $user->update(['avatar' => $path]);

        return back()->with('success', '头像上传成功');
    }

    /**
     * 显示浏览历史
     */
    public function history()
    {
        $this->middleware('auth');

        $user = auth()->user();

        $viewedPosts = $user->viewedPosts()
            ->with(['user', 'category', 'tags'])
            ->paginate(20);

        return Inertia::render('Profile/History', [
            'viewedPosts' => $viewedPosts,
        ]);
    }

    /**
     * 显示我的文章
     */
    public function myPosts()
    {
        $this->middleware('auth');

        $user = auth()->user();

        $posts = Post::where('user_id', $user->id)
            ->with(['category', 'tags'])
            ->withCount('comments')
            ->latest()
            ->paginate(10);

        return Inertia::render('Profile/MyPosts', [
            'posts' => $posts,
        ]);
    }

    /**
     * 显示我的草稿
     */
    public function drafts()
    {
        $this->middleware('auth');

        $user = auth()->user();

        $drafts = Post::where('user_id', $user->id)
            ->where('status', 'draft')
            ->with(['category', 'tags'])
            ->latest()
            ->paginate(10);

        return Inertia::render('Profile/Drafts', [
            'drafts' => $drafts,
        ]);
    }

    /**
     * 显示账户设置
     */
    public function settings()
    {
        $this->middleware('auth');

        return Inertia::render('Profile/Settings', [
            'user' => auth()->user(),
        ]);
    }

    /**
     * 更新账户设置
     */
    public function updateSettings(Request $request)
    {
        $this->middleware('auth');

        $user = auth()->user();

        $validated = $request->validate([
            'email' => 'required|email|unique:users,email,' . $user->id,
            'password' => 'nullable|string|min:8|confirmed',
            'allow_email_notifications' => 'boolean',
        ]);

        if (!empty($validated['password'])) {
            $validated['password'] = bcrypt($validated['password']);
        } else {
            unset($validated['password']);
        }

        $user->update($validated);

        return back()->with('success', '账户设置更新成功');
    }

    /**
     * 显示通知页面
     */
    public function notifications()
    {
        $this->middleware('auth');

        return Inertia::render('Profile/Notifications', [
            'user' => auth()->user(),
        ]);
    }

    /**
     * 显示收藏页面
     */
    public function favorites()
    {
        $this->middleware('auth');

        return Inertia::render('Profile/Favorites', [
            'user' => auth()->user(),
        ]);
    }

    /**
     * 显示关注/粉丝页面
     */
    public function follows()
    {
        $this->middleware('auth');

        return Inertia::render('Profile/Follows', [
            'user' => auth()->user(),
        ]);
    }
}